<template>
  <div class="app-container">
    <div class="mainbox">
      <div class="button-box">
        <countDownButton ref="countDown" @start="startTime" @end="endRecord" />
        <el-button
          type="primary"
          class="end-record"
          :disabled="disabledEnd"
          @click="endRecord"
        >结束录制</el-button>
        <el-button type="primary" @click="screenshot">截图</el-button>
      </div>
      <div class="monitor-play" @contextmenu.prevent v-if="!loading">
        <!-- <video controls autoplay muted
               ref="videoPlayer" id="videoElement" class="video-view">你的浏览器不支持 <code>video</code> 标签。</video> -->
        <video-player class="video-player vjs-custom-skin video-view" ref="videoPlayer" :options="options"
                      @error="handleError" crossOrigin="anonymous" id="videoPlayer"
                      @canplay="handleCanplay"  @pause="onPlayerPause($event)"></video-player>
        <monitor-error :visible="!success" :name="monitorName" :code="videoCode" />
      </div>
    </div>
  </div>
</template>

<script>
import monitorError from './components/monitorError'
import countDownButton from './components/countDownBtn'
// eslint-disable-next-line import/no-cycle
import { getVideo, qryFileIdByCode, startRecord, stopRecord } from '@/api/monitorPlay/playView'
import { getPlayUrl, screenImage } from '@/api/videoFusion/monitorGroup'
import { cloud } from '@/framework/utils/request'
// 引入样式
import 'video.js/dist/video-js.css'
import 'vue-video-player/src/custom-theme.css'

const options = {
  playbackRates: [], // 可选择的播放速度
  autoplay: true, // 如果true,浏览器准备好时开始回放。
  muted: true, // 默认情况下将会消除任何音频。
  loop: false, // 视频一结束就重新开始。
  // preload: 'auto',
  language: 'zh-CN',
  // aspectRatio: '16:9',
  sources: [
    {
      type: 'application/x-mpegURL',
      src: ''
    }
  ],
  notSupportedMessage: '前方视频信号中断，请稍后再试。',
  loading: true,
  controlBar: {
    timeDivider: true, // 当前时间和持续时间的分隔符
    durationDisplay: true, // 显示持续时间
    remainingTimeDisplay: true, // 是否显示剩余时间功能
    fullscreenToggle: true, // 全屏按钮
    playToggle: false
  }
}

export default {
  name: 'PlayView',
  components: { monitorError, countDownButton },
  data() {
    return {
      disabledEnd: true,
      countTime: '00:00:00',
      timer: null,
      options: null,
      mediaRecorder: null,
      recordedBlobs: [],
      isRecording: false,
      success: true,
      loading: false,
      monitorId: '',
      playType: '',
      fileId: '',
      videoCode: '',
      monitorName: '',
      playing: false,
      recordId: '',
      playId: ''
    }
  },
  mounted() {
    this.getData()
    window.addEventListener('beforeunload', this.handleTabClose)
  },
  beforeDestroy() {
    this.stopRecords()
    this.stopPlay()
    clearInterval(this.timer)
    window.removeEventListener('beforeunload', this.handleTabClose)
  },
  methods: {
    handleTabClose(event) {
      // setTimeout(() => {
      this.stopRecords()
      this.stopPlay()
      // })
      // event.returnValue = '确定要离开此页面吗？'
    },
    stopRecords() {
      if (this.recordId) {
        stopRecord(this.recordId).then(() => {
          this.recordId = ''
        })
      }
    },
    stopPlay() {
      if (this.playId) {
        stopRecord(this.playId)
      }
    },
    onPlayerPause($event, index) {
      this.$refs.videoPlayer.player.play()
    },
    getData() {
      const { monitorId, playType, fileId, videoCode, monitorName, monitorAddr } = this.$route.query
      this.monitorId = monitorId
      this.playType = playType
      this.fileId = fileId
      this.loading = true
      options.loading = true
      this.videoCode = videoCode
      this.monitorName = monitorName
      if (fileId) {
        options.sources[0].src = `${location.origin}${process.env.VUE_APP_BASE_API}${cloud.file}/sysFileInfo/publicDownload?fileId=${this.$route.query.fileId}`
        this.options = options
        this.loading = false
        this.playType = 1
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '监控数据加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (monitorId) {
        getPlayUrl({ playType, monitorId, monitorAddr }).then((res) => {
          setTimeout(() => {
            options.sources[0].src = res.data.httpPlayUrl
            this.options = options
            this.success = res.success
            this.playId = res.data.id
            loading.close()
            this.loading = false
          }, 20000)
        }).catch(() => {
          this.success = false
          loading.close()
          this.loading = false
        })
        return
      }
      if (videoCode) {
        qryFileIdByCode(videoCode).then((res) => {
          options.sources[0].src = `${location.origin}${process.env.VUE_APP_BASE_API}${cloud.file}/sysFileInfo/publicDownload?fileId=${res.data}`
          this.options = options
          this.fileId = res.data
          this.playType = 1
        }).finally(() => {
          loading.close()
          this.loading = false
        })
      }
    },
    handleCanplay() {
      this.success = true
      this.playing = true
    },
    handleError() {
      this.success = false
      this.playing = false
    },
    screenshot() {
      if (!this.playing) {
        return
      }
      // 调用后端接口
      screenImage({
        playUrl: options.sources[0].src,
        playType: this.playType || 2,
        monitorId: this.monitorId,
        videoFileInfoId: this.fileId
      }).then((res) => {
        this.$message({
          message: res.success ? '截图成功' : res.message,
          type: res.success ? 'success' : 'error'
        })
      })
    },
    startTime() {
      if (!this.playing) {
        return
      }
      startRecord({
        playUrl: this.options.sources[0].src,
        playType: this.playType || 2,
        monitorId: this.monitorId
      }).then((res) => {
        this.recordId = res.data.id
        this.disabledEnd = false
        this.$refs.countDown.startTiming()
      })
    },
    endRecord() {
      this.stopRecords()
      this.disabledEnd = true
      this.$refs.countDown.save()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background-color: #efefef
}
.mainbox {
  margin: 10px;
  background-color: #fff;
  box-shadow: 0px 4px 8px 2px rgba(0, 0, 0, 0.04),
              0px 2px 6px 0px rgba(0, 0, 0, 0.06),
              0px 0px 4px 0px rgba(0, 0, 0, 0.08);
}
.button-box {
  margin-bottom: 10px;
}
.monitor-play {
  position: relative;
  // width: 200px;
  height: calc(100vh - 97.6px);
  // background-color: pink;
  font-size: 24px;
  .video-view {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
::v-deep .end-record.is-disabled {
  color: #C0C4CC;
}
</style>
<style lang="scss">
.monitor-play {
  .video-js {
    height: 100%;
  }
}
</style>
